package org.wisdom.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.wisdom.response.Result;
import org.wisdom.utils.JwtUtils;
import org.wisdom.utils.UserContext;

import java.io.IOException;

@Component
public class AuthFilter implements Filter {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    ObjectMapper objectMapper;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 若无需校验的路径, 则直接放行
        if (antPathMatcher.match("/auth/**", request.getServletPath()) || request.getServletPath().equals("/chat")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 校验token
        Claims claims;
        try {
            String authorization = request.getHeader("Authorization");
            if (authorization == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(objectMapper.writeValueAsString(Result.error("未登录！")));
                return;
            }
            String token = authorization.substring(7);
            claims = jwtUtils.parseJwt(token);

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(Result.error("未登录！")));
            return;
        }

        // 将用户数据保存到上下文
        UserContext.setUser((Long) claims.get("id"));

        // 放行
        filterChain.doFilter(servletRequest, servletResponse);

        // 删除用户数据
        UserContext.removeUser();
    }
}
